package com.forumdemo.forum.services.impl;

import com.forumdemo.forum.common.AppResult;
import com.forumdemo.forum.common.ResultCode;
import com.forumdemo.forum.dao.ArticleReplyMapper;
import com.forumdemo.forum.exception.ApplicationException;
import com.forumdemo.forum.model.ArticleReply;
import com.forumdemo.forum.services.IArticleReplyService;
import com.forumdemo.forum.services.IArticleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2023-10-23
 * Time: 22:13
 */

@Slf4j
@Service
public class ArticleReplyServiceImpl implements IArticleReplyService {
    @Resource
    private ArticleReplyMapper articleReplyMapper;
    @Resource
    private IArticleService articleService;



    @Override
    public void create(ArticleReply articleReply) {
        // 非空校验
        if (articleReply == null
        || articleReply.getArticleId() == null
        || articleReply.getPostUserId() == null
        || !StringUtils.hasLength(articleReply.getContent())) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 设置默认值
        articleReply.setReplyId(null);
        articleReply.setReplyUserId(null);
        articleReply.setLikeCount(0);
        articleReply.setState((byte) 0);
        articleReply.setDeleteState((byte) 0);
        Date date = new Date();
        articleReply.setCreateTime(date);
        articleReply.setUpdateTime(date);
        // 写回会数据库
        int row = articleReplyMapper.insertSelective(articleReply);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        // 更新帖子表中的回复数
        articleService.addOneReplyCountById(articleReply.getArticleId());
        // 打印日志
        log.info("恢复成功，articleId=" + articleReply.getArticleId() + "，userId=" + articleReply.getPostUserId());
    }

    @Override
    public List<ArticleReply> selectByArticleId(Long articleId) {
        // 非空校验
        if (articleId == null || articleId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 调用 DAO，返回结果
        return articleReplyMapper.selectByArticleId(articleId);
    }
}
